package com.cpd.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cpd.blog.common.utils.CurrentUser;
import com.cpd.blog.dto.Article.CommentParam;
import com.cpd.blog.dto.Article.CommentVo;
import com.cpd.blog.dto.Result;
import com.cpd.blog.dto.User.UserVo;
import com.cpd.blog.entity.Comment;
import com.cpd.blog.manager.mapper.CommentsMapper;
import com.cpd.blog.service.ArticleService;
import com.cpd.blog.service.CommentsService;
import com.cpd.blog.service.UserService;
import lombok.RequiredArgsConstructor;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Copydown
 * @date 2021/8/17 22:04
 */
@Service
@RequiredArgsConstructor
public class CommentsServiceImpl implements CommentsService {

    private final CommentsMapper commentsMapper;

    private final UserService userService;

    private final ArticleService articleService;

//    private final CommentsManager commentsManager;

    @Override
    public Result commentByArticleId(Long id) {
        //根据文章id 查询评论列表
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getArticleId, id);
        queryWrapper.eq(Comment::getLevel, 1);
        List<Comment> comments = commentsMapper.selectList(queryWrapper);
        List<CommentVo> commentVoList = copyList(comments);

        return Result.success(commentVoList);
    }

    @Override
    public Result comment(CommentParam commentParam) {
        UserVo userVo = CurrentUser.get();
        Comment comment = new Comment();
        comment.setArticleId(commentParam.getArticleId());
        comment.setAuthorId(Long.parseLong(userVo.getId()));
        comment.setContent(commentParam.getContent());
        comment.setCreateDate(System.currentTimeMillis());
        Long parent = commentParam.getParent();
        // TODO：评论区盖楼功能
        if (parent == null || parent == 0) {
            comment.setLevel(1);
        } else {
            comment.setLevel(2);
        }
        comment.setParentId(parent == null ? 0 : parent);
        Long toUserId = commentParam.getToUserId();
        comment.setToUid(toUserId == null ? 0 : toUserId);

        // TODO：应建立 Management 层，serviceImpl 不该出现  mapper
        if (commentsMapper.insert(comment) != 1) {
            // TODO: 状态记录到 ErrCode下
            return Result.fail(-1, "评论失败");
        }
        // TODO：可考虑异步
        if (!articleService.commitIncr(commentParam.getArticleId())) {
            return Result.fail(-1, "评论数自增失败");
        }
        return Result.success(comment);
    }

    @Override
    public Result deleteByArticleId(Long articleId) {
//        commentsManager.logicDeleteByIdWithFill(articleId);
        return null;
    }

    private List<CommentVo> copyList(List<Comment> comments) {
        List<CommentVo> commentVoList = new ArrayList<>();
        for (Comment comment : comments) {
            commentVoList.add(copy(comment));
        }
        return commentVoList;
    }

    private CommentVo copy(Comment comment) {
        CommentVo commentVo = new CommentVo();
        BeanUtils.copyProperties(comment, commentVo);
        commentVo.setId(String.valueOf(comment.getId()));
        commentVo.setCreateDate(new DateTime(comment.getCreateDate()).toString("yyyy-MM-dd HH:mm"));

        //根据作者id 查询作者信息
        Long authorId = comment.getAuthorId();
        UserVo userVo = this.userService.findUserVoById(authorId);
        commentVo.setAuthor(userVo);

        //如果 level= 1，查询是否有子评论，有则通过评论id 进行查询
        Integer level = comment.getLevel();

        List<CommentVo> commentVoList = findCommentsByParentId(comment.getId());
        commentVo.setChildrens(commentVoList);
        if (level > 1) {
            Long toUid = comment.getToUid();
            UserVo toUserVo = userService.findUserVoById(toUid);
            commentVo.setToUser(toUserVo);
        }
        return commentVo;
    }

    private List<CommentVo> findCommentsByParentId(Long id) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getParentId, id);
        queryWrapper.eq(Comment::getLevel, 2);

        return copyList(commentsMapper.selectList(queryWrapper));
    }
}
